package cn.mengfly.testnrz.netty.encoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author Mengfly
 */
public class MessageToByteEncoderTest {

   public static class Integer2ByteEncoder extends MessageToByteEncoder<Integer> {

        @Override
        protected void encode(ChannelHandlerContext ctx, Integer msg, ByteBuf out) {
            out.writeInt(msg);
            System.out.println("encoder Integer = " + msg);
        }
    }



    public static void main(String[] args) {
        ChannelInitializer<EmbeddedChannel> ri = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(new Integer2ByteEncoder());
            }
        };

        EmbeddedChannel channel = new EmbeddedChannel(ri);
        for (int i = 0; i < 100; i++) {
            channel.write(i);
        }
        channel.flush();
        ByteBuf buf = channel.readOutbound();
        while (null != buf) {
            System.out.println("o = " + buf.readInt());
            buf = channel.readOutbound();
        }
    }
}
